package com.example.anni.zhuzhoujia.xiaowan;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.anni.zhuzhoujia.R;
import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;

import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.List;
import java.util.Map;

/**
 * Created by Anni on 2016/6/28.
 */
public class FansNumRecyclerViewAdapter extends RecyclerView.Adapter<MyViewHold3> {
    private LayoutInflater mInflater;
    private List<Map<String, String>> mDatas;
    private Context mContext;
    private Effectstype effect; //弹出对话框的动画类型

    public FansNumRecyclerViewAdapter() {
    }

    public FansNumRecyclerViewAdapter(Context context, List<Map<String, String>> datas) {
        this.mContext = context;
        this.mDatas = datas;
        mInflater = LayoutInflater.from(context);
    }

    //自定义监听事件
    public interface OnItemClickListener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    //创建View
    @Override
    public MyViewHold3 onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.fans_adapter, parent, false);
        MyViewHold3 myViewHold3 = new MyViewHold3(view);
        return myViewHold3;
    }

    //实现View
    @Override
    public void onBindViewHolder(final MyViewHold3 holder, final int position) {
        //设置点击时间回调
        if (mOnItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int layoutPosition = holder.getLayoutPosition();
                    mOnItemClickListener.onItemClick(holder.itemView, layoutPosition);
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int layoutPosition = holder.getLayoutPosition();
                    mOnItemClickListener.onItemLongClick(holder.itemView, layoutPosition);
                    return false;
                }
            });
        }
        //设置昵称
        if (mDatas.get(position).get("gender") != null) {
            holder.tvFansNickName.setText(mDatas.get(position).get("nickName"));
        } else {
            holder.tvFansNickName.setText("未设置");
        }
        //设置性别
        if (mDatas.get(position).get("gender") != null) {
            if (mDatas.get(position).get("gender").equals("BOY")) {
                holder.tvFansGender.setText("男");
            } else if (mDatas.get(position).get("gender").equals("GRIL")) {
                holder.tvFansGender.setText("女");
            } else if (mDatas.get(position).get("gender").equals("UNKONW")) {
                holder.tvFansGender.setText("保密");
            }
        } else {
            holder.tvFansGender.setText("未设置");
        }

        //设置头像
        ImageOptions options = new ImageOptions.Builder()
                .setCircular(true)
                .setFailureDrawableId(R.mipmap.header_whilte)
                .build();
        if (mDatas.get(position).get("avatar").length() == 0 && mDatas.get(position).get("avatar").equals("")) {
            holder.ivFansAvatar.setImageResource(R.mipmap.null_head_image);
        } else {
            x.image().bind(holder.ivFansAvatar,
                    "http://tr.zzapi.gson.cn/" + mDatas.get(position).get("avatar"),
                    options
            );
        }

        //指定用户的关注列表,动态显示列表是否已关注
        RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/user/get/attentions");
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
        String uid = sp.getString("id", "");
        params.addQueryStringParameter("page", "1");
        params.addQueryStringParameter("rows", "100");
        params.addQueryStringParameter("id", uid);
        x.http().get(params, new CallBackAdapter<String>() {
            @Override
            public void onSuccess(String s) {
                JSONObject obj = JSON.parseObject(s);
                //Log.e("obj----*-", s);
                boolean success = obj.getBoolean("success");
                JSONArray arr = obj.getJSONArray("data");
                if (success) {
                    String userId = mDatas.get(position).get("id");
                    //Log.e("userId----*-", userId);
                    for (int i = 0; i < arr.size(); i++) {
                        String loginId = arr.getJSONObject(i).getString("id");
                        //Log.e("LoginId----*-", loginId);
                        if (userId.equals(loginId)) {
                            holder.btnIsFans.setText("取消关注");
                            break;
                        } else {
                            holder.btnIsFans.setText("未关注");
                        }
                    }
                }
            }
        });
        //点击按钮是否关注和取消关注
        holder.btnIsFans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (holder.btnIsFans.getText().equals("未关注")) {
                    RequestParams params =
                            new RequestParams("http://tr.zzapi.gson.cn/api/user/attention");
                    String fansUid = mDatas.get(position).get("id");
                    params.addQueryStringParameter("attentionUid", fansUid);
                    x.http().get(params, new CallBackAdapter<String>() {
                        @Override
                        public void onSuccess(String s) {
                            JSONObject obj = JSON.parseObject(s);
                            Boolean success = obj.getBoolean("success");
                            if (success) {
                                holder.btnIsFans.setText("取消关注");
                                //Log.e("message----*-", obj.getString("message").substring(0, 4));
                                Toast.makeText(mContext, obj.getString("message"), Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                } else {
                    effect = Effectstype.Fadein;
                    final NiftyDialogBuilder niftyDialog = NiftyDialogBuilder.getInstance(mContext);
                    niftyDialog
                            .withTitle("取消关注")
                            .withTitleColor("#ffffffff")
                            .withDividerColor("#ffffffff")
                            .withDialogColor("#ffffffff")
                            .withMessage("亲，你真的要取消关注")
                            .withMessageColor("#ffffffff")
                            .isCancelableOnTouchOutside(true)
                            .withDuration(700)
                            .withEffect(effect)
                            .withButton1Text("确定")
                            .withButton2Text("取消")
                            .setCustomView(R.layout.cancel_content_login, mContext)
                            .setButton1Click(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    RequestParams params =
                                            new RequestParams("http://tr.zzapi.gson.cn/api/user/attention");
                                    String attentionUid = mDatas.get(position).get("id");
                                    params.addQueryStringParameter("attentionUid", attentionUid);
                                    x.http().get(params, new CallBackAdapter<String>() {
                                        @Override
                                        public void onSuccess(String s) {
                                            JSONObject obj = JSON.parseObject(s);
                                            Boolean success = obj.getBoolean("success");
                                            if (success) {
                                                holder.btnIsFans.setText("未关注");
                                                //Log.e("message----*-", obj.getString("message").substring(0, 4));
                                                Toast.makeText(mContext, obj.getString("message"), Toast.LENGTH_LONG).show();
                                            }
                                        }
                                    });
                                    niftyDialog.dismiss();
                                }
                            })
                            .setButton2Click(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    niftyDialog.dismiss();
                                }
                            })
                            .show();
                }
            }
        });


    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    //点击取消关注，删除关注行
    public void deleteDatas(int position) {
        mDatas.remove(position);
        notifyItemRemoved(position);
    }

    //显示个人信息
    public void showPersonalInformation(final int position) {
        final String id;
        final String[] attentions = new String[1];
        final String[] fans = new String[1];
        //获取关注人数接口
        RequestParams params = new RequestParams("http://tr.zzapi.gson.cn/api/user/get/attentionAndFansNum");
        id = mDatas.get(position).get("id");
        params.addQueryStringParameter("uid", id);
        x.http().get(params, new CallBackAdapter<String>() {
            @Override
            public void onSuccess(String s) {
                JSONObject obj = JSON.parseObject(s);
                Boolean success = obj.getBoolean("success");
                if (success) {
                    ImageView ivAppointImg;
                    TextView ivAppointAttentions;
                    //获得内容布局
                    View view = LayoutInflater.from(mContext).inflate(R.layout.show_personal_information, null);
                    ivAppointImg = (ImageView) view.findViewById(R.id.iv_appoint_img);
                    ivAppointAttentions = (TextView) view.findViewById(R.id.tv_appoint_attentions);
                    //设置指定用户头像
                    if (mDatas.get(position).get("avatar").length() == 0 && mDatas.get(position).get("avatar").equals("")) {
                        ivAppointImg.setImageResource(R.mipmap.null_head_image);
                    } else {
                        ImageOptions options = new ImageOptions.Builder()
                                .setRadius(10)
                                .setSquare(true)
                                .setCircular(true)
                                .setFailureDrawableId(R.mipmap.header_whilte)
                                .build();
                        x.image().bind(ivAppointImg,
                                "http://tr.zzapi.gson.cn/" + mDatas.get(position).get("avatar"),
                                options
                        );
                    }
                    String area = mDatas.get(position).get("area");
                    if (area != null) {
                        if (area.equals("LL")) {
                            ivAppointAttentions.setText("所属区域：醴陵");
                        } else if (area.equals("SF")) {
                            ivAppointAttentions.setText("所属区域：石峰区");
                        } else if (area.equals("YL")) {
                            ivAppointAttentions.setText("所属区域：炎陵县");
                        } else if (area.equals("YLSFFQ")) {
                            ivAppointAttentions.setText("所属区域：云龙示范区");
                        } else if (area.equals("ZZX")) {
                            ivAppointAttentions.setText("所属区域：株洲县");
                        } else if (area.equals("YX")) {
                            ivAppointAttentions.setText("所属区域：攸县");
                        } else if (area.equals("TY")) {
                            ivAppointAttentions.setText("所属区域：天元区");
                        } else if (area.equals("LS")) {
                            ivAppointAttentions.setText("所属区域：芦淞区");
                        } else if (area.equals("HT")) {
                            ivAppointAttentions.setText("所属区域：荷塘区");
                        } else if (area.equals("CL")) {
                            ivAppointAttentions.setText("所属区域：茶陵县");
                        }
                    } else {
                        ivAppointAttentions.setText("未设置");
                    }

                    //注册时间
                    String dateline = mDatas.get(position).get("dateline");
                    //关注人数
                    attentions[0] = obj.getJSONObject("data").getString("attentions");
                    //粉丝人数
                    fans[0] = obj.getJSONObject("data").getString("fans");
                    effect = Effectstype.SlideBottom;
                    final NiftyDialogBuilder niftyDialog = NiftyDialogBuilder.getInstance(mContext);
                    niftyDialog
                            .withTitle(mDatas.get(position).get("nickName"))
                            .withTitleColor(R.color.title_nor)
                            .withDividerColor("#ffffffff")
                            .withDialogColor("#ffffffff")
                            .withMessage("注册于：" + dateline)
                            .withMessageColor(R.color.title_nor)
                            .isCancelableOnTouchOutside(true)
                            .withDuration(700)
                            .withEffect(effect)
                            .withButton1Text("关注   " + attentions[0])
                            .withButton2Text("粉丝   " + fans[0])
                            .withButtonDrawable(R.drawable.photo_cancel_selector)
                            .setCustomView(view, mContext)
                            .setButton1Click(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    RequestParams params =
                                            new RequestParams("http://tr.zzapi.gson.cn/api/user/get/attentionAndFansNum");
                                    params.addQueryStringParameter("uid", id);
                                    x.http().get(params, new CallBackAdapter<String>() {
                                        @Override
                                        public void onSuccess(String s) {
                                            JSONObject obj = JSON.parseObject(s);
                                            Boolean success = obj.getBoolean("success");
                                            if (success) {
                                                String attentions = obj.getJSONObject("data").getString("attentions");
                                                if (attentions.equals("0")) {
                                                    Toast.makeText(mContext, "没有关注的人数", Toast.LENGTH_LONG).show();
                                                } else {
                                                    Intent intent = new Intent(mContext, AttentionsRecyclerView.class);
                                                    intent.putExtra("uid", id); //把id传过去
                                                    mContext.startActivity(intent);
                                                }
                                            }
                                        }
                                    });

                                }
                            })
                            .setButton2Click(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //获取用户的粉丝人数和关注人数
                                    RequestParams params =
                                            new RequestParams("http://tr.zzapi.gson.cn/api/user/get/attentionAndFansNum");
                                    params.addQueryStringParameter("uid", id);
                                    x.http().get(params, new CallBackAdapter<String>() {
                                        @Override
                                        public void onSuccess(String s) {
                                            JSONObject obj = JSON.parseObject(s);
                                            Boolean success = obj.getBoolean("success");
                                            if (success) {
                                                String fans = obj.getJSONObject("data").getString("fans");
                                                if (fans.equals("0")) {
                                                    Toast.makeText(mContext, "暂时没有粉丝", Toast.LENGTH_LONG).show();
                                                } else {
                                                    Intent intent = new Intent(mContext, FansNumRecyclerView.class);
                                                    intent.putExtra("uid", id); //把id传过去
                                                    mContext.startActivity(intent);
                                                }
                                            }
                                        }
                                    });

                                }
                            })
                            .show();
                }
            }
        });
    }
}

class MyViewHold3 extends RecyclerView.ViewHolder {
    TextView tvFansNickName;
    TextView tvFansGender;
    ImageView ivFansAvatar;
    Button btnIsFans;


    public MyViewHold3(View itemView) {
        super(itemView);
        tvFansNickName = (TextView) itemView.findViewById(R.id.tv_fans_nickName);
        ivFansAvatar = (ImageView) itemView.findViewById(R.id.iv_fans_avatar);
        tvFansGender = (TextView) itemView.findViewById(R.id.tv_fans_gender);
        btnIsFans = (Button) itemView.findViewById(R.id.btn_is_fans);
    }
}

